<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Link, Search, Delete, Plus } from '@element-plus/icons-vue'
import { type AddHostForm, type HostDto, type CapCluster } from '@/api/cap'
import {
  addHost,
  getHostPage,
  delHost,
  getClusterList,
  noticeHostUploadApps,
  noticeHostRegister,
  hostBindCluster,
} from '@/api/cap'
import issueLinkDialog from './issueLink.vue'
import { ElMessage } from 'element-plus'

import dayjs from 'dayjs'

const searchDto = reactive({
  ip: '',
  guaProtocol: '',
  pageNum: 1,
  pageSize: 10,
})

const dialogForm = reactive<AddHostForm>({})

const showDialog = ref(false)
const isAddForm = ref(true)
const isAddCertify = ref(true) // 是否为直接添加凭证

const tableData = ref<HostDto[]>([])
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
})
const clusterList = ref<CapCluster[]>([])

const clickSearchBtn = () => {
  searchDto.pageNum = 1
  getHostPage(searchDto).then((res) => {
    tableData.value = res.list
    pagination.total = res.total
  })
}

onMounted(() => {
  clickSearchBtn()
  getClusterList().then((res) => {
    clusterList.value = res
  })
})

const clickAddBtn = () => {
  isAddForm.value = true
  dialogForm.status = 1
  dialogForm.guaProtocol = 'rdp'
  dialogForm.clusterId = ''
  isAddCertify.value = true
  showDialog.value = true
}

const clickSubDialogForm = () => {
  if (isAddForm.value) {
    const addForm: AddHostForm = {
      uid: dialogForm.uid,
      ip: dialogForm.ip,
      guaPort: Number(dialogForm.guaPort),
      status: dialogForm.status,
      guaProtocol: dialogForm.guaProtocol,
      clusterId: dialogForm.clusterId,
      bindUserId: '0',
      account: '',
      password: '',
      description: dialogForm.description,
    }
    if (isAddCertify.value) {
      addForm.account = dialogForm.account
      addForm.password = dialogForm.password
    }
    if (addForm.clusterId == '') addForm.clusterId = '0'
    addHost(addForm).then(() => {
      showDialog.value = false
      clickSearchBtn()
    })
  }
}
const clickDelBtn = (id: string) => {
  delHost(id).then(() => {
    clickSearchBtn()
  })
}

const childDialogRef = ref()
const clickIsssueLinkBtn = (hostId: string) => {
  childDialogRef.value.openDialog(hostId)
}

const clickScanAppBtn = (hostId: string) => {
  noticeHostUploadApps(hostId)
    .then(() => {
      ElMessage({
        message: '通知成功.',
        type: 'success',
      })
    })
    .catch((e) => {
      console.log(e)
      ElMessage.error('通知客户端上报应用信息时发生错误：', e)
    })
}
const clickRegisterBtn = (hostId: string) => {
  noticeHostRegister(hostId)
    .then(() => {
      ElMessage({
        message: '通知成功.',
        type: 'success',
      })
    })
    .catch((e) => {
      console.log(e)
      ElMessage.error('通知客户端上报注册信息时发生错误：', e)
    })
}

const bindClusterDialog = ref(false)
const bindClusterForm = reactive({
  hostId: '',
  clusterId: '',
})
const clickBindClusterBtn = (hostId: string) => {
  bindClusterForm.hostId = hostId
  bindClusterDialog.value = true
}
const SubBindClusterBtn = () => {
  hostBindCluster(bindClusterForm.hostId, bindClusterForm.clusterId).then(() => {
    bindClusterDialog.value = false
    clickSearchBtn()
  })
}
</script>

<template>
  <div>
    <el-dialog v-model="bindClusterDialog" title="绑定集群" width="500">
      <el-form :model="bindClusterForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="集群">
          <el-select v-model="bindClusterForm.clusterId" clearable placeholder="选择集群">
            <el-option
              v-for="item in clusterList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bindClusterDialog = false">取消</el-button>
          <el-button type="primary" @click="SubBindClusterBtn"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <issueLinkDialog ref="childDialogRef"></issueLinkDialog>
    <el-dialog v-model="showDialog" :title="isAddForm ? '添加主机' : '更新主机'" width="500">
      <el-form :model="dialogForm" label-width="auto" style="max-width: 600px">
        <el-form-item label="唯一码">
          <el-input v-model="dialogForm.uid" />
        </el-form-item>
        <el-form-item label="IP">
          <el-input v-model="dialogForm.ip" />
        </el-form-item>
        <el-form-item label="端口">
          <el-input v-model="dialogForm.guaPort" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">维护</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="协议">
          <el-radio-group v-model="dialogForm.guaProtocol">
            <el-radio value="rdp">RDP</el-radio>
            <el-radio value="vnc">VNC</el-radio>
            <el-radio value="sh">SH</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="集群">
          <el-select v-model="dialogForm.clusterId" clearable placeholder="选择集群">
            <el-option
              v-for="item in clusterList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="凭证信息">
          <el-radio-group v-model="isAddCertify">
            <el-radio :value="true">添加凭证</el-radio>
            <el-radio :value="false">选择凭证</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号" v-show="isAddCertify">
          <el-input v-model="dialogForm.account" />
        </el-form-item>
        <el-form-item label="密码" v-show="isAddCertify">
          <el-input v-model="dialogForm.password" />
        </el-form-item>
        <el-form-item label="描述" v-show="isAddCertify">
          <el-input v-model="dialogForm.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="clickSubDialogForm"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-card>
      <el-row class="mb-5">
        <el-col>
          <el-input
            v-model="searchDto.ip"
            class="max-w-xs mr-5"
            placeholder="按IP信息过滤"
            style="width: 240px"
            clearable
          />
          <el-select
            v-model="searchDto.guaProtocol"
            placeholder="按协议过滤"
            clearable
            class="mr-5"
            style="width: 140px"
          >
            <el-option label="VNC协议" value="vnc" />
            <el-option label="RDP协议" value="rdp" />
            <el-option label="SH协议" value="sh" />
          </el-select>
          <el-button type="primary" :icon="Search" @click="clickSearchBtn">查询</el-button>
          <el-button type="primary" :icon="Plus" @click="clickAddBtn">添加</el-button>
        </el-col>
      </el-row>

      <el-table :data="tableData" stripe style="width: 100%" show-overflow-tooltip>
        <el-table-column type="index" width="50" label="#" />
        <el-table-column prop="hostInfo.ip" label="IP" />
        <el-table-column prop="hostInfo.guaPort" label="连接端口" width="80" />
        <el-table-column prop="hostInfo.guaProtocol" label="协议" width="80">
          <template #default="scope">
            <div v-if="scope.row.hostInfo.guaProtocol == 'cap'">
              <el-tooltip
                effect="dark"
                content="cap 协议属于RDP协议的扩展，不能直接添加，请使用 cap client 自动注册！"
                placement="top"
              >
                <el-tag type="warning">cap</el-tag>
              </el-tooltip>
            </div>
            <el-tag v-else type="success">{{ scope.row.hostInfo.guaProtocol }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hostInfo.uid" label="唯一码" />
        <el-table-column label="集群信息">
          <template #default="scope">
            <el-tag :type="scope.row.hostInfo.clusterId == '0' ? 'info' : 'success'">{{
              scope.row.hostInfo.clusterId == '0' ? '未绑定' : scope.row.clusterInfo.name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hostInfo.uid" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.hostInfo.status ? 'success' : 'info'">{{
              scope.row.hostInfo.status ? '正常' : '维护'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">
            {{ dayjs(new Date(scope.row.hostInfo.createdAt * 1000)).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="100">
          <template #default="scope">
            <el-link :icon="Link" type="primary" class="mr-3">连接</el-link>
            <el-link
              :icon="Delete"
              type="primary"
              class="mr-3"
              @click="clickDelBtn(scope.row.hostInfo.id)"
              >删除</el-link
            >
            <el-dropdown>
              <el-link type="primary">
                更多<el-icon><ArrowDown /></el-icon>
              </el-link>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>补充参数</el-dropdown-item>
                  <el-dropdown-item @click="clickIsssueLinkBtn(scope.row.hostInfo.id)"
                    >发布链接</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.hostInfo.guaProtocol != 'cap'"
                    @click="clickRegisterBtn(scope.row.hostInfo.id)"
                    >重新注册</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.hostInfo.guaProtocol != 'cap'"
                    @click="clickScanAppBtn(scope.row.hostInfo.id)"
                    >扫描应用</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.hostInfo.guaProtocol != 'cap'"
                    @click="clickBindClusterBtn(scope.row.hostInfo.id)"
                    >绑定集群</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-5"
        layout="prev, pager, next"
        :hide-on-single-page="pagination.total / pagination.pageSize < 2"
        :total="pagination.total"
      />
    </el-card>
  </div>
</template>

<style scoped>
.width {
  width: 200px;
}
.el-dropdown {
  display: contents;
}
</style>
